package com.cy.pj.sys.service.aspect;


import com.cy.pj.common.annotation.AApproval;
import com.cy.pj.common.factory.ServiceFactory;
import com.cy.pj.common.service.JgerpAssert;
import com.cy.pj.common.web.pojo.Input;
import com.cy.pj.common.web.pojo.JSONObject;
import com.cy.pj.sys.dao.UserDao;
import com.cy.pj.sys.service.IApprovalDetailService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

@Aspect
@Component
public class ApprovalAspect {
    @Autowired
    UserDao userDao;

    /**
     * 审批四个接口的参数校验及参数注入
     *
     * @param point
     * @throws Throwable
     */
    @Around("execution(* com.cy.pj.sys.controller.ApprovalController.*(com.cy.pj.common.web.pojo.Input))")
    public JSONObject approvalValid(ProceedingJoinPoint point) throws Throwable {
        Input input = (Input) point.getArgs()[0];
        System.out.println((point.getSignature().getName() + "入参：" + input));
        // 根据注解注入参数
        Signature signature = point.getSignature();
        MethodSignature msg = (MethodSignature) signature;
        Method method = point.getTarget().getClass().getMethod(msg.getName(), msg.getParameterTypes());
        AApproval annotation = method.getAnnotation(AApproval.class);
        String opType = annotation.opType();
        if (!StringUtils.isEmpty(opType)) {
            input.setUser(userDao.selectUser(input.getUser().getUserName()));
        }
        // 获取service
        IApprovalDetailService service = ServiceFactory.getService(input.getApproval().getModuleId());
        JgerpAssert.notNull(service, "不存在该服务");
        // 装填service
        input.setService(service);
        // 执行后序方法
        JSONObject res = (JSONObject) point.proceed();
        System.out.println((point.getSignature().getName() + "出参：" + res));
        return res;
    }
}
